package me.cloudcat.develop.mongodb;

import me.cloudcat.develop.entity.Role;
import me.cloudcat.develop.entity.User;
import me.cloudcat.develop.entity.type.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Mongodb测试
 *
 * @author zhenzhong.wang
 * @date 2018/7/8
 */
@Service
public class MongoService {

  @Autowired
  private MongoTemplate template;

  @Autowired
  private UserRepository userRep;

  /**
   * 测试查询，JPA方式
   *
   * @return
   */
  public User testQuery() {
//    User user = mongoTemplate.findOne(new Query(Criteria.where("username").is("admin")), User.class);
    User user = userRep.findByUsername("root");
    List<User> all = userRep.findAll();
    return user;
  }

  /**
   * 测试保存，JPA方式
   */
  public void testSave() {
    User user = new User();
    user.setUsername("root");
    user.setPassword("123456");
    user.setEmail("jiafei@123.com");
    userRep.save(user);
  }

  /**
   * 测试保存，template方式
   */
  public void testSaveWithTemplate() {
    Role role = new Role();
    role.setName("超级管理员");
    role.setStatus(Status.ENABLE);
    template.save(role);
  }

  /**
   * 测试更新，template方式
   */
  public void testUpdateWithTemplate() {
    Role role = new Role();
    role.setName("超级管理员");
    role.setStatus(Status.ENABLE);
    template.updateFirst(new Query(new Criteria().where("name").regex("^超级")),
        new Update().set("status", Status.DISABLE), Role.class);
  }

  /**
   * 测试删除，template方式
   */
  public void testDeleteWithTemplate() {
    template.remove(new Query(new Criteria().where("status").is(Status.DISABLE)), Role.class);
  }
}
